//
//  YCKeyboardManager.m
//  KeyboardManager
//
//  Created by 唐可雄 on 2018/7/27.
//  Copyright © 2018年 swustyc. All rights reserved.
//

#import "YCKeyboardManager.h"

#import "UIResponder+FirstResponder.h"

@interface YCKeyboardManager()

@property (assign, nonatomic) UIView *focusView;

@end

@implementation YCKeyboardManager

#pragma mark - Initial

+ (void)load {
    [self performSelectorOnMainThread:@selector(sharedInstance) withObject:nil waitUntilDone:NO];
}

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static YCKeyboardManager *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[YCKeyboardManager alloc] init];
        manager.autoToolbar = YES;
        [manager addKeywordNotificationObservers];
    });
    return manager;
}

#pragma mark - Keyword Notification

/**
 添加键盘通知监听器
 */
- (void)addKeywordNotificationObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywordWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywordDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywordWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywordDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywordWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

/**
 获取某个控件的视图控制器

 @param view 子控件
 @return 视图控制器
 */
- (UIViewController *)viewControllerOf:(UIView *)view {
    id nextResponder = [view nextResponder];
    if (nextResponder) {
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            if ([[nextResponder parentViewController] isKindOfClass:[UINavigationController class]]) {
                return nextResponder;
            } else if ([[nextResponder parentViewController] isKindOfClass:[UITabBarController class]]) {
                return nextResponder;
            } else if ([[nextResponder parentViewController] isKindOfClass:[UISplitViewController class]]) {
                return nextResponder;
            } else if ([nextResponder parentViewController] == nil){
                return nextResponder;
            } else {
                return [self viewControllerOf:nextResponder];
            }
        } else {
            return [self viewControllerOf:nextResponder];
        }
    }
    return nil;
}

- (void)keywordWillShow:(NSNotification *)notification {
    self.focusView = [UIResponder currentResponder];
    [self addToolbar];
    
    [self keywordWillChangeFrame:notification];
}

- (void)keywordDidShow:(NSNotification *)notification {
    
}

- (void)keywordWillHide:(NSNotification *)notification {

}

- (void)keywordDidHide:(NSNotification *)notification {
    self.focusView = nil;
}

- (void)keywordWillChangeFrame:(NSNotification *)notification {
    CGRect end = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    UIViewController *vc = [self viewControllerOf:self.focusView];
    if (vc) {
        if (end.origin.y == [UIScreen mainScreen].bounds.size.height) {
            // 键盘消失
            vc.view.frame = CGRectMake(vc.view.frame.origin.x, 0, vc.view.frame.size.width, vc.view.frame.size.height);
            [vc.view.superview setNeedsLayout];
            [vc.view.superview layoutIfNeeded];
        } else {
            // 键盘出现或者变化高度
            CGRect rect = [self.focusView.superview convertRect:self.focusView.frame toView:[UIApplication sharedApplication].keyWindow];
            if (rect.origin.y + rect.size.height > end.origin.y) {
                [UIView animateWithDuration:0.25 animations:^{
                    vc.view.frame = CGRectMake(vc.view.frame.origin.x, vc.view.frame.origin.y +  end.origin.y - rect.origin.y - rect.size.height, vc.view.frame.size.width, vc.view.frame.size.height);
                }];
            }
            NSLog(@"");
        }
    }
}

#pragma mark - Toolbar

- (void)addToolbar {
    if (self.autoToolbar) {
        if (!self.focusView.inputAccessoryView) {
            UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
            toolbar.tintColor = self.tintColor;
            [toolbar setItems:@[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDidTap)]]];
            if ([self.focusView respondsToSelector:@selector(setInputAccessoryView:)]) {
                [self.focusView performSelector:@selector(setInputAccessoryView:) withObject:toolbar];
                [self.focusView reloadInputViews];
            }
        }
    }
}

- (void)doneDidTap {
    [self.focusView resignFirstResponder];
}

@end
